import json
import re

from django import http
from django.contrib.auth import login, authenticate, logout
from django.core.mail import send_mail
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View

from apps.users.models import User


# 验证用户名
from apps.users.utils import generate_verify_email_url,check_verify_email_token
from celery_tasks.email.tasks import send_email_active
from utils.views import LoginRequiredJSONMixin


class UsernameCountView(View):

    def get(self, request, username):
        # - 1 接收 用户名
        print(username)
        # #   - 2 根据用户名查询数据库，查询数量有几个
        try:
            count = User.objects.filter(username=username).count()
        except Exception as e:
            print(e)
            return JsonResponse({"code": '15', 'errmsg': '数据异常'})

        #   - 3 返回json数据
        response = JsonResponse({"count": count, "code": "1", "errmsg": "OK"})

        return response


# 注册
class RegisterView(View):

    def post(self, request):

        body_byte = request.body
        data_json = json.loads(body_byte)
        print(data_json)
        username = data_json.get('username')
        password = data_json.get('password')
        password2 = data_json.get('password2')
        mobile = data_json.get('mobile')
        sms_code = data_json.get('sms_code')
        allow = data_json.get('allow')

        if not all([username, password, password2, mobile, sms_code, allow]):
            return JsonResponse({'code': 400, 'errmsg': '数据上传错误'})

        # 判断用户名是否是5-20个字符
        if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username):
            return http.JsonResponse({'code': 400, 'errmsg': 'username格式有误!'})
        # 判断密码是否是8-20个数字
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return http.JsonResponse({'code': 400, 'errmsg': 'password格式有误!'})
        # 判断两次密码是否一致
        if password != password2:
            return http.JsonResponse({'code': 400, 'errmsg': '两次输入不对!'})
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'code': 400, 'errmsg': 'mobile格式有误!'})
        # 判断是否勾选用户协议
        if allow != True:
            return http.JsonResponse({'code': 400, 'errmsg': 'allow格式有误!'})
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, "errmsg": '注册失败'})

        # 把用户信息保存到session中
        login(request, user)

        return JsonResponse({'code': 0, 'errmsg': 'ok'})


# 登录
class LoginView(View):

    def post(self, request):

        # 1. 接收json数据
        body = request.body
        print(body)
        data_dict = json.loads(body)

        username = data_dict.get('username')
        password = data_dict.get('password')
        remembered = data_dict.get('remembered')

        # 2. 验证数据是否为空
        if not all([username, password]):
            return JsonResponse({'code': 400, 'errmsg': '数据为空'})

        # 多账号登录
        if re.match('^1[3-9]\d{9}$', username):
            User.USERNAME_FIELD = 'mobile'
        else:
            # 根据用户名从数据库获取user对象返回
            User.USERNAME_FIELD = 'username'

        # 对用户名和密码验证
        user = authenticate(username=username, password=password)
        if not user:

            return JsonResponse({'code': 400, 'errmsg': '用户名密码错误'})

        # 状态保持
        login(request, user)

        # 5. 判断是否记住登录
        if remembered:
            # 如果记住：设置为两周有效
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)



        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username, max_age=360000 * 24 * 15)
        # print(111)
        return response

# 退出登录
class LoginOut(View):
    def delete(self,request):
        # 清理session
        logout(request)



        # 退出登录，重定向到登录页
        response = JsonResponse({'code':0, 'errmsg':'ok'})

        response.delete_cookie('username')

        return response


class UserInfoView(LoginRequiredJSONMixin,View):

    def get(self,request):

        print(request.user.username)

        return JsonResponse({'code':0,'errmsg': 'ok','info_data':{
            'username':request.user.username,
            'email': request.user.email,
            'mobile':request.user.mobile,
            'email_active': request.user.username
            # 'email_active':False
        }})


# 用户中心保存email

class EmailSaveView(LoginRequiredJSONMixin,View):
    def put(self,request):
        # 1.获取json数据  转为字典
        body = request.body
        data_dict = json.loads(body)

        email = data_dict.get('email')

        # 校验
        if not email:
            return JsonResponse({'code':300,'errmsg':'邮箱不存在'})


        # 保存到数据库
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code':400,'errmsg':'邮箱保存失败了'})

        # subject = '马金涛'
        # message= '<p>尊敬的用户您好！</p>'\
        #          'p>感谢您使用美多商城。</p>' \
        #          'p>您的邮箱为：{} 。请点击此链接激活您的邮箱：</p>'.format(email) \
        #          '<a href="{}"></a>'
        # from_email = "马金涛<1161401654@qq.com>"

        # recipient_list = [email,'2336657109@qq.com','1161401654@qq.com','547329428@qq.com']
        #
        # send_mail(subject=subject,message=message,from_email=from_email,recipient_list=recipient_list)
        #

        verify_url = generate_verify_email_url(request.user)

        message = '<p>尊敬的用户您好！</p><p>感谢您使用美多商城。</p>' \
                       '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        send_email_active.delay(email,message)




        return JsonResponse({'code':0,'errmsg':'OK'})

# 激活邮箱
class EmailVerifyView(View):

    def put(self,request):
        # 1. 接收请求(put)数据
        # 2. 获取token
        token = request.GET.get('token')

        # 3. 对token解密  获取解密数据里的userid
        user_id =  check_verify_email_token(token)

        # 如果获取不到说明过期
        if not user_id:
            return JsonResponse({'code':400, 'message':'激活邮件已经过期'})
        # 根据user_id去数据库查询
        try:
            user= User.objects.get(id=user_id)

        except Exception as e:
            print(e)
            return JsonResponse({'code':405,'errmsg':'当前的用户不存在'})

        # 把查到的user对象的 email_active字段 改为true 不要忘记save
        user.email_active=True
        user.save()
        return JsonResponse({'code':0,'errmsg':'激活成功'})






